Skip to content

设计模式 (Design Patterns)

发布-订阅模式 (Publish-Subscribe / EventEmitter)

javascript
class EventEmitter {
  constructor() {
    this.events = {};
  }

  // 订阅事件
  on(type, handler) {
    if (!this.events[type]) {
      this.events[type] = [];
    }
    this.events[type].push(handler);
  }

  // 发布事件
  emit(type, ...args) {
    if (this.events[type]) {
      this.events[type].forEach(handler => {
        handler.apply(this, args);
      });
    }
  }

  // 取消订阅
  off(type, handler) {
    if (!this.events[type]) return;
    this.events[type] = this.events[type].filter(h => h !== handler);
  }

  // 只执行一次
  once(type, handler) {
    const wrapper = (...args) => {
      handler.apply(this, args);
      this.off(type, wrapper);
    };
    this.on(type, wrapper);
  }
}

// 示例 usage
// const bus = new EventEmitter();
// bus.on('click', () => console.log('Clicked!'));
// bus.emit('click');

MIT Licensed | Keep Learning.